package com.gitee.candy.encry;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;

/**
 * 对称加密
 */
public class EncryptDESUtils {

    private Key key;

    public static final EncryptDESUtils me = new EncryptDESUtils();

    private static final String CHARSET = "UTF-8";

    private static final String DES = "DES";

    private static final String CDEL_KEY = "miyaomiyao"; // 不少于8位

    public EncryptDESUtils() {
        this.setkey(CDEL_KEY);
    }

    private void setkey(String keyStr) {
        try {
            DESKeySpec e = new DESKeySpec(keyStr.getBytes(CHARSET));
            SecretKeyFactory objKeyFactory = SecretKeyFactory.getInstance(DES);
            key = objKeyFactory.generateSecret(e);
        } catch (Exception var4) {
            throw new RuntimeException(var4);
        }
    }

    public final String encrypt(String str) {
        byte[] bytes = str.getBytes();
        try {
            Cipher e = Cipher.getInstance(DES);
            e.init(1, key);
            byte[] encryptStrBytes = e.doFinal(bytes);
            return new String(EncryptBASE64Utils.encodeByte(encryptStrBytes), CHARSET);
        } catch (Exception var5) {
            throw new RuntimeException(var5);
        }
    }

    public final String decrypt(String str) {
        try {
            byte[] e = EncryptBASE64Utils.decode(str.getBytes(CHARSET));
            Cipher cipher = Cipher.getInstance(DES);
            cipher.init(2, key);
            e = cipher.doFinal(e);
            return new String(e);
        } catch (Exception var4) {
            throw new RuntimeException();
        }
    }

    public static void main(String[] args) {
        String str = "宝剑分从磨砺出，梅花香自苦寒来";
        String encrypt = me.encrypt(str);
        System.out.println(encrypt);
        String decrypt = me.decrypt(encrypt);
        System.out.println(decrypt);
    }

}
